package com.xbdun.web.validatebmp.upload.service.receive;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.validation.ValidationException;

import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.xbdun.ValidateWebApplication;
import com.xbdun.common.entity.XbdunItem;
import com.xbdun.facade.validatebmp.constant.UploadBusinessType;
import com.xbdun.facade.validatebmp.constant.WatermarkPostion;
import com.xbdun.facade.validatebmp.exceptions.ValidateBizException;
import com.xbdun.facade.validatebmp.upload.core.UploadFileBASE64;
import com.xbdun.facade.validatebmp.upload.core.UploadVo;
import com.xbdun.facade.validatebmp.upload.result.UploadOpenResult;
import com.xbdun.web.validatebmp.upload.core.UpLoadUtil;
import com.xbdun.web.validatebmp.upload.core.UploadFile;
import com.xbdun.web.validatebmp.upload.core.service.UploadOpenService;

import lombok.extern.slf4j.Slf4j;

/**
* @ClassName: BaseUploadOpenService
* @Description: 基础上传组件
* @author zhanggt 360730440@qq.com
* @date 2017年5月13日 下午1:38:31
*/
@Slf4j
public abstract class BaseUploadOpenService implements UploadOpenService {
	public UploadOpenResult uploadByBASE64(WatermarkPostion watermarkPostion, String orgCode,UploadFileBASE64 upFileBASE64) throws ValidateBizException {
		InputStream inputStream = null;
		UploadOpenResult baseResult = new UploadOpenResult();
		try {
			Assert.notNull(upFileBASE64,"上传数据不能为空");
			Assert.notNull(upFileBASE64.getFile(),"上传的具体文件不能为空");			
			inputStream = upFileBASE64.getInputStream();
			//上传文件检查（base64）
			if(StringUtils.isEmpty(upFileBASE64.getFile())){
				 baseResult.setBizException(ValidateBizException.UPLOAD_NULL_ERROR);
				 return baseResult;
			}
			//必填参数检查
			if(upFileBASE64.getUploadBusinessType()==null||upFileBASE64.getFileSize()==0){
				 baseResult.setBizException(ValidateBizException.UPLOAD_ALLOW_TYPE_ERROR);
				 return baseResult;
			}
			//检查文件大小
			if(inputStream.available()>upFileBASE64.getFileSize()){
				 baseResult.setBizException(ValidateBizException.UPLOAD_SIZE_ERROR);
				 return baseResult;
			}			
			String extName=upFileBASE64.getExtName();
			boolean flag = false;
			if(!StringUtils.isEmpty(extName)){
				for(String type : upFileBASE64.getUploadBusinessType().getAllowFileType()){
					if(extName.equals(type)){
						flag=true;
						break;
					}
				}
			}
			//检查文件类型
			if(!flag){
				 baseResult.setBizException(ValidateBizException.UPLOAD_FORMAT_ERROR);
				 return baseResult;
			}
			
			XbdunItem<String, String> saveFolder=upFileBASE64.getUploadBusinessType().getSaveFolder(ValidateWebApplication.getSaveFolder());
			String fileName=UpLoadUtil.createFileName(extName);
			
			log.debug("保存文件目录,{}",saveFolder);
			log.debug("保存文件名称：{}",fileName);
			
			FileUtils.copyInputStreamToFile(inputStream, new File(saveFolder.first+fileName));
			UploadVo uploadVo = handleUpload(upFileBASE64.getReturnFormat(),upFileBASE64.getUploadBusinessType(),saveFolder.first+fileName,saveFolder.second+fileName,watermarkPostion,orgCode);
			baseResult.setData(uploadVo);
			return baseResult;
		} catch (Exception e) {
			log.error("uploadBASE64",e);
			closeInputStream(inputStream);
			throw new ValidationException(e);
		}finally{
			closeInputStream(inputStream);
		}
	}

	public UploadVo upload(String upfmt,WatermarkPostion watermarkPostion, String apiClientNo, UploadFile upFile,InputStream inputStream) throws ValidateBizException {
		try {
			if(StringUtils.isEmpty(upFile)){
				Assert.notNull(upFile,"上传文件不能为空");
			}
			Assert.notNull(inputStream,"上传文件流不存在");
			XbdunItem<String, String> saveFolder=upFile.getUploadBusinessType().getSaveFolder(ValidateWebApplication.getSaveFolder());
			String extName = ".jpg";
			if(!StringUtils.isEmpty(upFile.getMultipartFile())){
				extName = upFile.getExtName();
			}
			String fileName=UpLoadUtil.createFileName(extName);
			log.debug("保存文件目录,{}",saveFolder);
			log.debug("保存文件名称：{}",fileName);
			
			FileUtils.copyInputStreamToFile(inputStream, new File(saveFolder.first+fileName));
			return handleUpload(upfmt,upFile.getUploadBusinessType(),saveFolder.first+fileName,saveFolder.second+fileName,watermarkPostion,apiClientNo);
		} catch (Exception e) {
			log.error("uploadBase64",e);
			closeInputStream(inputStream);
			throw new ValidationException(e);
		}finally{
			closeInputStream(inputStream);
		}
	}

	//关闭文件流
	private final void closeInputStream(InputStream inputStream){
		if(null!=inputStream){
			try {
				inputStream.close();
				inputStream=null;
			} catch (IOException e) {
			}
		}
	}
	/**
	 * 处理上传文件
	 * @param returnFormat	上传保存后返回的图片
	 * @param BusinessTypeUtil 上传文件业务类型
	 * @param realPath 上传文件保存的物理完整路径
	 * @param contextPath 上传文件保存的相对路径
	 * @param watermarkPostio 水印位置 {@link WatermarkPostion}
	 * @param orgCode 机构编号 
	 * @return 上传源文件保存后结果{@link UploadVo}
	 * @throws Exception
	 */
	protected abstract UploadVo handleUpload(String returnFormat,UploadBusinessType uploadBusinessType,String realPath,String contextPath,WatermarkPostion watermarkPostion,String orgCode) throws Exception;
}
